package com.jinhuhang.u2.ui.mainview;

import android.content.pm.PackageInfo;
import android.content.pm.PackageManager;
import android.net.Uri;
import android.os.Environment;

import com.jinhuhang.u2.MyApplication;
import com.jinhuhang.u2.common.api.Api;
import com.jinhuhang.u2.common.api.RetrofitUtils;
import com.jinhuhang.u2.common.base.presenter.impl.BasePresenterImpl;
import com.jinhuhang.u2.common.constant.Constant;
import com.jinhuhang.u2.entity.CheckActivity;
import com.jinhuhang.u2.entity.Code;
import com.jinhuhang.u2.entity.UserBean;
import com.jinhuhang.u2.entity.VersionEntity;
import com.jinhuhang.u2.ui.MainActivity;
import com.jinhuhang.u2.util.http.HttpWrapper;
import com.jinhuhang.u2.util.http.HttpWrapperList;
import com.jinhuhang.u2.util.http.Result;
import com.jinhuhang.u2.util.http.ResultList;
import com.jinhuhang.u2.util.http.T;

import java.util.Map;

/**
 * Created by caoxiaowei on 2017/9/27.
 */
public class MainPresenter extends BasePresenterImpl implements  MainContract.Presenter{



    private MainContract.View mView;

    public MainPresenter(MainContract.View context){
        mView =context;
        mView.setPresenter(this);
    }

    @Override
    public void getData() {
        addSubscription(RetrofitUtils.getInstance().build()
                .checkVersion(0,"android")
                .compose(T.defaultScheduler())
                .subscribe(new ResultList<HttpWrapperList<VersionEntity>>() {

                    @Override
                    protected void onSuccess(HttpWrapperList<VersionEntity> o) {
                        String forcedUpdate = o.getSingleData().getForcedUpdate();
                        if(forcedUpdate.equals("1")){
                            int versionNum = 0;
                            try {
                                versionNum = getVersionNum();
                            } catch (Exception e) {
                                e.printStackTrace();
                            }
                            if(versionNum!=0){
                                String currentVersion =  o.getSingleData().getVersion();
                                int vcode=Integer.parseInt(currentVersion.split(":")[1]);
                                //取本地版本
                                if(vcode>versionNum){
                                    mView.check(currentVersion);
                                    updateVersion();
                                }
                            }
                        }

                    }

                }));
    }

    @Override
    public void updateVersion() {



        FileDownLoader.get().download(Api.VERSIONUPDATE, "download/", new FileDownLoader.OnDownloadListener() {
            @Override
            public void onDownloadSuccess(Uri uri) {
              mView.install(uri);
            }
            @Override
            public void onDownloading(int progress) {
                if (progress==100){
                    mView.progressNUM(progress);
                }

            }
            @Override
            public void onDownloadFailed() {

            }
        });

    }
    @Override
    public void Login(Map<String, String> map) {
      //  mView.showDialog("登录中...");
        RetrofitUtils.getInstance().build()
                .login(map)
                .compose(T.D())
                .subscribe(new Result<HttpWrapper<UserBean>>() {
                    @Override
                    protected void onSuccess(HttpWrapper<UserBean> o) {
                        mView.onResultLogin(o);
                    }

                    @Override
                    protected void onFinish() {
                   //     mView.dissDialog();
                    }
                });
    }

    @Override
    public void checkActivity() {
        RetrofitUtils.getInstance().build()
                .checkActivity(MainActivity.uid)
                .compose(T.D())
                .subscribe(new Result<HttpWrapper<CheckActivity>>() {
                    @Override
                    protected void onSuccess(HttpWrapper<CheckActivity> o) {
                        if (o.code==200)
                        mView.startActivity(o.getData());
                    }

                    @Override
                    protected void onFinish() {
                        mView.dissDialog();
                    }
                });
    }
    @Override
    public void getPhone() {
        RetrofitUtils.getInstance().build()
                .getPhone("0")
                .compose(T.D())
                .subscribe(new ResultList<HttpWrapperList<Code>>() {
                    @Override
                    protected void onSuccess(HttpWrapperList<Code> o) {
                        if (o.code==200)
                            Constant.phone=o.getSingleData().getHotline();
                    }

                    @Override
                    protected void onFaild() {
                        super.onFaild();
                    }

                    @Override
                    protected void onFinish() {
                        mView.dissDialog();
                    }
                });
    }

    @Override
    public void setRead() {
        addSubscription(RetrofitUtils.getInstance().build()
                .setRead(MainActivity.uid)
                .compose(T.defaultScheduler())
                .subscribe(new ResultList<HttpWrapperList<String>>() {

                    @Override
                    protected void onSuccess(HttpWrapperList<String> o) {
                        if (o.getCode()==200){

                        }
                    }

                }));
    }

    @Override
    public void checkToken() {
        addSubscription(RetrofitUtils.getInstance().build()
                .checkToken(MainActivity.userbean.getUserId(),MainActivity.userbean.getToken())
                .compose(T.defaultScheduler())
                .subscribe(new ResultList<HttpWrapperList<String>>() {

                    @Override
                    protected void onSuccess(HttpWrapperList<String> o) {
                        if (o.getCode()==200){
                            mView.checkTokenResult();
                        }else {
                            //token 失效
                            MainActivity.checktoken=false;
                            if (o.getCode()!=301) {
                                MainActivity.tip=o.getInfo();
                            }
                        }
                    }

                }));
    }
    @Override
    public void checkToken1() {
        addSubscription(RetrofitUtils.getInstance().build()
                .checkToken(MainActivity.userbean.getUserId(),MainActivity.userbean.getToken())
                .compose(T.defaultScheduler())
                .subscribe(new ResultList<HttpWrapperList<String>>() {

                    @Override
                    protected void onSuccess(HttpWrapperList<String> o) {
                        mView.jumpTo(o);
                    }

                }));
    }
    public static String getSDpath() {
        String sdPath = null;
        // 判断sdcard存在不存在
        if (Environment.getExternalStorageState().equals(
                Environment.MEDIA_MOUNTED)) {
            sdPath = Environment.getExternalStorageDirectory().getPath() + "/";
        }
        return sdPath;
    }
    public static  int getVersionNum() throws Exception {
        // 获取packagemanager的实例
        PackageManager packageManager = MyApplication.getContext().getPackageManager();
        // getPackageName()是你当前类的包名，0代表是获取版本信息
        PackageInfo packInfo = packageManager.getPackageInfo( MyApplication.getContext().getPackageName(),0);
        int versionNum = packInfo.versionCode;
        return versionNum;
    }
    public static  String getVersionName() throws Exception {
        // 获取packagemanager的实例
        PackageManager packageManager = MyApplication.getContext().getPackageManager();
        // getPackageName()是你当前类的包名，0代表是获取版本信息
        PackageInfo packInfo = packageManager.getPackageInfo( MyApplication.getContext().getPackageName(),0);
        String versionNum = packInfo.versionName;
        return versionNum;
    }
}
